//
//  SYYSearchBar.m
//  UPhone
//
//  Created by xhkj on 2021/8/31.
//

#import "SYYSearchBar.h"

@interface SYYSearchBar ()<UISearchBarDelegate>

@property (nonatomic, copy)void(^TouchBlock)(void);
@property (nonatomic, copy)void(^BeginEditingBlock)(void);
@property (nonatomic, copy)void(^EndEditingBlock)(NSString *searchText);

@end

@implementation SYYSearchBar

- (instancetype)initTitleViewSearchBarWithFrame:(CGRect)frame title:(NSString *)title touchBlock:(void(^)(void))touchBlock beginEditingBlock:(void(^)(void))beginEditingBlock endEditingBlock:(void(^)(NSString *searchText))endEditingBlock{
    if (self = [super initWithFrame:frame]) {
        
        
        self.TouchBlock = touchBlock;
        self.BeginEditingBlock = beginEditingBlock;
        self.EndEditingBlock = endEditingBlock;
        
        self.barStyle = UIBarStyleDefault;
        
        self.backgroundColor = [UIColor clearColor];
        self.backgroundImage = [UIImage imageWithColor:[UIColor clearColor]];
        self.placeholder = [NSString stringWithFormat:@" %@",title];

        CGFloat width = frame.size.width;
        CGFloat height = frame.size.height;
        UIImage *searchTFBackImg = [[UIImage imageWithColor:HHColorHex(0xEEEEF7) size:CGSizeMake(width, height)] imageByRoundCornerRadius:height/2.0];
        [self setSearchFieldBackgroundImage:searchTFBackImg forState:UIControlStateNormal];
        
        
        UITextField *searchField;
        if (@available(iOS 13.0, *)) {
            searchField = self.searchTextField;
        } else {
            searchField = [self valueForKey:@"_searchTextField"];
        }
        UIButton *clearButton = [searchField valueForKey:@"_clearButton"];
        [clearButton addTarget:self action:@selector(clearSearchBar:) forControlEvents:UIControlEventTouchUpInside|UIControlEventTouchDown];

        
        self.delegate = self;
    }
    return self;
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if (searchText.length > 15) {
        searchBar.text = [searchText substringWithRange:NSMakeRange(0, 15)];
    }
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    if (self.TouchBlock) {
        self.TouchBlock();
        return NO;
    }
    if (self.BeginEditingBlock) {
        self.BeginEditingBlock();
        return YES;
    }
    return NO;
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    [searchBar resignFirstResponder];
    
    if (self.EndEditingBlock) {
        self.EndEditingBlock(searchBar.text);
    }
}


- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    if (self.EndEditingBlock) {
        self.EndEditingBlock(searchBar.text);
    }
}


- (void)clearSearchBar:(UIButton *)button
{
    self.text = @"";
    self.SearchClearBlock?self.SearchClearBlock(self.text):nil;
}



@end

